import style from '../css/PatientLists.module.scss'
import { Flex, Form ,Input , Modal ,DatePicker,Select, Button, Table , Space , message } from 'antd';
import { SearchOutlined , PlusCircleOutlined} from '@ant-design/icons'
import type { TableProps ,  } from 'antd';
import { useEffect, useState } from 'react';
import { patientlogoff, patientserch, patinetlists } from '../utils/request';
import moment from 'moment'
import Padination from '../components/Pagination';
import { useNavigate } from 'react-router';
function PatientLists() {
    const [form] = Form.useForm();
    const [formOne] = Form.useForm()
    const navigate = useNavigate()
    const { RangePicker } = DatePicker;
    // 数据表格
    interface DataType {
        patient_id: number;
        Medicalrecord: string;
        Medicalcard: string;
        name: string;
        sex: string;
        IDtype: string;
        Idcard: string;
        status: string;
        Filingtime: string
    }

    const columns: TableProps<DataType>['columns'] = [
        {
            title: '病历号',
            dataIndex: 'Medicalrecord',
            key: 'Medicalrecord',
            width: 112,
            //   render: (text) => <p>{text}</p>,
        },
        {
            title: '就诊卡号',
            dataIndex: 'Medicalcard',
            key: 'Medicalcard',
            width: 113
        },
        {
            title: '患者姓名',
            dataIndex: 'name',
            key: 'name',
            width: 104
        },
        {
            title: '性别',
            dataIndex: 'sex',
            key: 'sex',
            width: 83
        },
        {
            title: '证件类型',
            dataIndex: 'IDtype',
            key: 'IDtype',
            width: 104
        },
        {
            title: '证件号',
            dataIndex: 'Idcard',
            key: 'Idcard',
            render:(text)=><span>{text.substr(0, 4) + '************' + text.substr(-2)}</span>,
            width: 170
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 89,
            render: (text) => (text == '正常' ? <span style={{ color: '#00A76F' }}>{text}</span> : <span style={{ color: '#AAA' }}>{text}</span>)
        },
        {
            title: '建档时间',
            dataIndex: 'Filingtime',
            key: 'Filingtime',
            render:(text) =><span>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</span>,
            width: 167
        },
        {
            title: '操作',
            key: 'action',
            dataIndex: 'action',
            width: 160,
            render: (_, record) => (
                record.status == '正常' ?
                    <Space size="middle">
                        <a style={{ color: '#0468FF' }} onClick={() => details(record.patient_id)}>详情</a>
                        <a style={{ color: '#0468FF' }} onClick={()=> edit(record.patient_id)}>编辑</a>
                        <a style={{ color: '#FA6A1C' }} onClick={()=> logoff(record.patient_id)}>注销</a>
                    </Space>
                    :
                    <a style={{ color: '#0468FF' }} onClick={() => details(record.patient_id)}>详情</a>
            ),
        },
    ];
    // 渲染患者列表数据
    const [mockData,setmockData] = useState([])
    const [data,setData] = useState<DataType[]>([])
    useEffect(()=>{
        patinetlists().then(res=>{
            setmockData(res.data)
            setData(res.data.slice(0,10))
        }).catch(err=>{
            console.log(err)
        })
    },[])
    // 分页传递数据 
    const getshowsize=(data: any)=>{
        setData(mockData.slice((data.current-1)*data.pageSize,data.pageSize*data.current))
    }
    
    //表格操作
    const details = (i: number) => {
        console.log('详情',i)
        navigate('/index/patientmangent/PatientLists/PatientDetail?id='+i)
    }
    const edit = (i: number) =>{
        console.log('编辑',i)
        navigate('/index/patientmangent/PatientRegistration?id='+i)

    }
    const { TextArea } = Input;
    const [loading, setLoading] = useState(false);
    const [logoffId,setLogoffId] = useState(0)
    const handleOk = () => {
        // console.log('确认')
        formOne.validateFields().then(values => {
            console.log('Validated values: ', values);
            setLoading(true)
            setTimeout(() => {
                patientlogoff({
                    id:logoffId,
                    ...values
                }).then(res=>{
                    console.log(res)
                    setmockData(res.data)
                    setData(res.data.slice(0,10))
                }).catch(err=>{
                    console.log(err)
                })
                setLoading(false)
                setIsDeleteModalVisible(false)
                formOne.resetFields()
                message.success(`注销操作成功！`);
            }, 2000);
        }).catch(info => {
            console.log('Validate Failed:', info);
        });
    };

    const handleCancel = () => {
        console.log('取消')
        setIsDeleteModalVisible(false)
        formOne.resetFields()
        message.warning('已取消操作')
    };
     const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);
    const logoff = (i: number) => {
        console.log('注销')
        setLogoffId(i)
        setIsDeleteModalVisible(true)
    }
    
    // 新建登记
    const insert=()=>{
        console.log('新建登记')
        navigate('/index/patientmangent/PatientRegistration')
    }
    // 搜索
    const search=()=>{
        console.log('搜索')
        form.validateFields().then(values => {
            console.log('Validated values: ', values);
            patientserch(values).then(res=>{
                console.log(res.data)
                setmockData(res.data)
                setData(res.data.slice(0,10))
            }).catch(err=>{
                console.log(err)
            })
        }).catch(info => {
            console.log('Validate Failed:', info);
        });

    }
    // 重置
    const reset=()=>{
        console.log('重置')
        form.resetFields();
        patinetlists().then(res=>{
            console.log(res.data)
            setmockData(res.data)
            setData(res.data.slice(0,10))
        }).catch(err=>{
            console.log(err)
        })
    }
    
    return ( 
        <>
            {/* 注销确认对话框 */}
            <Modal
                onOk={handleOk}
                onCancel={handleCancel}
                title={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E6%82%A3%E8%80%85%E5%88%97%E8%A1%A8/u2571.svg" alt="" />
                        <span style={{marginLeft:5}}>注销确认</span>
                    </div>
                }
                open={isDeleteModalVisible}
                footer={[
                    <Flex key='flex' justify='flex-end'>
                        <Button key="back" onClick={handleCancel} style={{height:32,marginRight:10}}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={loading} onClick={handleOk} style={{height:32}}>
                        注销
                        </Button>,
                    </Flex>
                  ]}
                width={375}
            >
                <Form
                    form={formOne}
                    style={{
                        marginTop: 20
                    }}
                >
                    <Form.Item className={style.itemstyle} rules={[{ required: true }]} label='注销原因' name='reson'>
                        <Select
                            style={{ width: 230, height: 32, borderRadius: 0 }}
                            placeholder='请选择'
                            options={[
                                { value: '销户', label: '销户' },
                                { value: '离院删档', label: '离院删档' },
                                { value: '更换信息', label: '更换信息' },
                                { value: '其他', label: '其他' },
                            ]}
                        />
                    </Form.Item>
                    <Form.Item className={style.itemstyle} label='注销备注' name='note'>
                        <TextArea style={{ width: 230, height: 80, borderRadius: 0, resize: 'none' }} rows={4} />
                    </Form.Item>
                </Form>
            </Modal>
            <div className={style.searchboxs}>
                <Form
                    form={form}
                    initialValues={{ status:'全部状态'}}
                >
                    <Flex align='center' >
                        <Form.Item label="就诊卡号" rules={[
                            {
                            max:8,min:8,message:'请输入8位有效就诊卡号'
                            },
                            {
                                pattern: /^[0-9]*[1-9][0-9]*$/,
                                message:'请输入有效数字'
                            },{
                                required:true
                            }
                        ]} name='Medicalcard' className={style.itemstyle}>
                            <Input style={{
                                width:200,
                                height:32
                            }} maxLength={8} placeholder='请输入'></Input>
                        </Form.Item>
                        <Form.Item label="证件号" name='Idcard' rules={[
                            {
                            max:18,min:18,message:'请输入18位有效证件号'
                            },
                            {
                                pattern: /^[0-9]*[1-9][0-9]*$/,
                                message:'请输入有效数字'
                            },{
                                required:true
                            }
                        ]} className={style.itemstyle}>
                            <Input style={{
                                width:200,
                                height:32
                            }} maxLength={18} placeholder='请输入'></Input>
                        </Form.Item>
                        <Form.Item label="患者姓名" name='name' rules={[{
                            pattern:/^[A-Za-z\u4e00-\u9fa5]+$/,
                            message:'请输入中文或英文'
                        },{
                            max:10,
                            message:'长度不超过10位'
                        },{
                            required:true
                        }]} className={style.itemstyle}>
                            <Input style={{
                                width:200,
                                height:32
                            }} placeholder='请输入'></Input>
                        </Form.Item>
                    </Flex>
                    <Flex align='center' justify='space-between' >
                        <Flex>
                            <Form.Item label='建档时间' name='Filingtime' className={style.itemstyle}>
                                <RangePicker allowClear></RangePicker>
                            </Form.Item>
                            <Form.Item label='状态'  name='status' className={style.itemstyle}>
                            <Select
                                allowClear
                                style={{ width: 200 ,height:32}}
                                options={[
                                    { value: '全部状态', label: '全部状态' },
                                    { value: '正常', label: '正常' },
                                    { value: '已注销', label: '已注销' },
                                ]}
                            />
                            </Form.Item>
                        </Flex>
                        <Flex style={{marginBottom:22}}>
                            <Button style={{
                                width:60,
                                height:32,
                                marginRight:20
                            }} onClick={()=>reset()}>重置</Button>
                            <Button style={{
                                width:75,
                                height:32,
                                backgroundColor:'#0460ff'
                            }} onClick={()=>search()} type="primary" icon={<SearchOutlined />}>
                                搜索
                            </Button>
                        </Flex>
                    </Flex>
                </Form>
            </div>
            <div className={style.datalists}>
                <Button className={style.insertButton} type="primary" icon={<PlusCircleOutlined />} onClick={()=>insert()}>新建登记</Button>
                <Table<DataType>  columns={columns} dataSource={data} className={style.custom_table} rowKey='patient_id' pagination={false} />
                {/* 分页器 */}
                <Padination total={mockData.length} showsize={getshowsize}></Padination>
            </div>
        </>
     );
}

export default PatientLists;

